<?php


require_once("inc.member.php");





$this_title=__($vars["title"])." &raquo; ".__("Registration");


$page_title=replace_tag(__("<%title%> &raquo; ").__("Registration"), array("<%title%>"=>__($vars["title"])));


$content_title=__("Register");





$r_position=array(1,2);


$r_position_d=array(1=>__("Left"),2=>__("Right"));


$r_link=array($uid,0);


$r_link_d=array($uid=>__("Yes"),0=>__("No"));


$r_gender=array("m", "f");


$r_gender_d=array("m"=>__("Male"), "f"=>__("Female"));


$country_code=$vars['common']['country_code'];


array_shift($country_code);


$country_code_t=$vars['common']['country_code_text'];


foreach($country_code_t as $code=>$cname){


 $country_code_d[$code]=__($cname);


}


$r_payment_channel=array('eswallet');


$r_payment_channel_d=array('eswallet'=>__($vars['eswallet_title'])." ".$vars['currency'].number_format($r_user['eswallet'], 2), 'twallet'=>$r_user['twallet']." ".__("free 3 start account(s)"), 'fwallet'=>$r_user['fwallet']." ".__("free 5 start account(s)"));

$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;

$r_package=$vars['r_package'];

$r_package_d=$vars['r_package_detail'];


$td_width=175;





require_once("inc.register_tab.php");





//#####AJAX CALL#####


if($_GET["aj"] && $_GET["check_ref"]){


	if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal')"))){


		$ajerrmsg=replace_tag(__("Sponsor ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));


	}else{


		$ajmsg=replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['username']));


	}


	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);


	print format_xml($xml);


	exit();


}





if($_GET["aj"] && $_GET["check_upline"]){


	if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal','n')"))){


		$ajerrmsg=replace_tag(__("Upline ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));


	}else{


		$ajmsg=replace_tag(__("Upline ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['username']));


	}


	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);


	print format_xml($xml);


	exit();


}


//#####END AJAX CALL#####





//#####REGISTER POST#####


if($_SESSION["user_register"] && $_POST["__req"]){


	/*##### ERROR CHECK #####*/


	$chk_arr="_name,_password,_email,_address,_address2,_city,_zip,_state,_mobileno,_bank_name,_bank_acc_no,_bank_swiftcode,_bank_branch,_signup_code";

	$chk_arr2=$chk_arr.",_username";
	$chk_arr2=explode(",", $chk_arr2);
	
	foreach($post_s as $f=>$v){


		if(in_array($f, $chk_arr2)){


			$data[$f]=$v;


		}


	}


	$errmsg=verify_form_data("users", $data);


	if(!$errmsg){


		//check referrer


		if($post_s["ref"]){


			if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal')"))){


				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['ref']))."<br />\n";


			}elseif($r_ref['activated'] != 'y'){


				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' is not activated and cannot sponsor new member."), array("<%rid%>"=>$post_h['ref']))."<br />\n";


			}else{


				$ref_found=1;


				$ref_id=$r_ref["id"];


			}


		}else{


			$ref_id=0;


		}


		//check placement


		if($post_s["matrix_upline"]){


			if(!$r_upline=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[matrix_upline]' and status in ('suspended','normal','n')"))){


				$errmsg.=replace_tag(__("Placement ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['matrix_upline']))."<br />\n";


			}else{
				$matrix_upline_info=get_user_detail_by_code($post_d['matrix_upline']);

				if(!in_array($post_s['matrix_position'], $r_position)){


					$errmsg.=__("Please select a placement position.")."<br />";


				}elseif(@mysql_num_rows(mysql_query("select * from $db->users where matrix_upline='$matrix_upline_info[id]' and matrix_position='$post_d[matrix_position]'"))){


					$errmsg.=__("The selected Placement ID and Placement Position is already occupied.")."<br />";


				}else{
					
					$matrix_upline_id = $matrix_upline_info["id"];
					
				}


			}


		}else{


			$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Upline ID")))."<br />";


		}


		if(!$errmsg){


			if($post_s['matrix_upline'] != $post_s['ref'] ){
				
				$sponsor = get_user_detail_by_code($post_s['ref']);
				$placement = get_user_detail_by_code($post_s['matrix_upline']);
				
				if(!is_group_matrix_downline_of($placement['id'], $sponsor['id'])){
					
					$errmsg.=__("The selected Upline ID is not in the network group of the Sponsor ID.")."<br />";	
					
				}

			}


		}

		$purchase = get_signup_code($post_s['_signup_code']);
		
		if($purchase['total_bv']<=0){


			$errmsg.=__("Invalid signup code.")."<br />";


		}else{
			
			$cost = $purchase['amount'];
			$bv = $purchase['total_bv'];
			
		}



		if($post_s["acc_type"]=="p"){



			//check dob


			$dob="$post_s[dob_year]-".pad_length($post_s["dob_month"], 2)."-".pad_length($post_s["dob_day"], 2);


			if(!@checkdate($post_s["dob_month"], $post_s["dob_day"], $post_s["dob_year"])){


				$errmsg=__("Invalid date format selected for DOB.")."<br />\n";


			}


			//check gender


			if(!in_array($post_s["gender"], $r_gender)){


				$errmsg.=__("Please specify Gender.")."<br />\n";


			}


		}elseif($post_s["acc_type"]=="c"){


			//check business reg no


			if(bis_reg_found($post_d["_bis_reg"])){


				$errmsg.=replace_tag(__("Company Reg. No. '<%bis_reg%>' belongs to another member."), array("<%bis_reg%>"=>$post_h['_ic']))."<br />\n";


			}


		}


		//check username


		if(username_found($post_d["_username"])){


			$errmsg.=replace_tag(__("The username '<%username%>' is not available, please choose another."), array("<%username%>"=>$post_h["_username"]))."<br />\n";


		}


		//check password


		if($post_s["_password"] != $post_s["password2"]){


			$errmsg.=__("Your entered passwords did not match.")."<br />\n";


		}


		//check email


		if(strlen($post_s['_email'])){


			if(!verify_email($post_s["_email"])){


				$errmsg.=__("Please provide a valid email address.")."<br />\n";


			}


		}


		//check terms


		if(!$post_s["terms"]){


			$errmsg.=replace_tag(__("You must agree to the Terms of Service of <%title%>."), array("<%title%>"=>__($vars["title"])))."<br />\n";


		}


	}


	//#####END ERROR CHECK#####





	$preview = $confirm = false;


	if(!$errmsg){


		if(!$post_s['__confirm'] && !$post_s['__edit']){


			$preview = true;


		}elseif($post_s['__confirm']){


			$confirm = true;


		}


	}





	//#####ADD TO DB#####


	if(!$errmsg && $confirm){


		$field_arr=$chk_arr2;


		for($i=0,$t=count($field_arr);$i<$t;$i++){
			
			if(substr($field_arr[$i], 1)=='signup_code') continue;

			$ufq.=($ufq? ", " : "").(substr($field_arr[$i], 0, 1) == '_'? substr($field_arr[$i], 1) : $field_arr[$i]);


			$uvq.=($uvq? ", " : "")."'".$post_d[$field_arr[$i]]."'";


		}


		$ufq.=", dob, gender";


		$uvq.=", '$dob', '$post_d[gender]'";


		$salt=generate_random_code(32);
		$enc_pass=md5($post_s["_password"].$salt).":".$salt;

		$password2=generate_random_code(6);
		$ewallet_enc_pass=md5($password2.$salt).":".$salt;
		
		$password3=generate_random_code(6);
		$epoint_enc_pass=md5($password3.$salt).":".$salt;

		$status='normal';


		$vc=generate_random_code(20);


		$rank_a = $purchase['rank_a'];
		$total_account = $vars['package'][$purchase['rank_a']]['account']; //use?
		$pool_share = $vars['package'][$purchase['rank_a']]['cp'];
		
		$datetime=ndate($vars["system_date_format"]);

		$is_free = '0';
		
		//if not pay then cannot use below code
		$sql="insert into $db->users (acc_type, is_stockist, ref, creator, cid, rank_a, matrix_upline, matrix_position, $ufq, ewallet_password, epoint_password, enc_password, ewallet_enc_password, epoint_enc_password, country, status, is_free, activated, activated_date, cdate, pool_share) values ('$post_d[acc_type]', 'n', '$ref_id', 'u', '$uid', '$rank_a', '$matrix_upline_id', '$post_d[matrix_position]', $uvq, '$password2', '$password3', '$enc_pass', '$ewallet_enc_pass', '$epoint_enc_pass', '$post_d[country]', '$status', $is_free, 'y', '$datetime', '$datetime', '$pool_share')";

		if(!mysql_query($sql)){


			$errmsg.=__("We have encountered some error and the registration process has been failed.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");


		}else{
			
			$new_uid=mysql_insert_id();
			$array_matrix_upline[0] = $new_uid;
			$matrix_upline = $new_uid;	
			
			mysql_query("update $db->users set code=id where id=".$new_uid);
			
			//$share_price = @mysql_result(mysql_query("select value from {$vars["dbi"]["prefix"]}settings where param='share_price' limit 1"), 0);
			//if($share_price<0) $share_price = 0;	
			
			if(!mysql_query("update $db->purchase set uid='$new_uid', member_sale='y', collected='y', collected_date='".$datetime."' where id='".$purchase['id']."' limit 1")){
				

				$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the signup code ".$post_s['signup_code']." could not be found.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";


			}


			


			//insert purchase record


			$first_sale = true;


			$total_bv = $total_dp = $total_rp = $vars['package'][$purchase['rank_a']]['bv'];
			$price = $vars['package'][$purchase['rank_a']]['price'];
			$total_cp = $vars['package'][$purchase['rank_a']]['cp'];
			$max_dlot = $vars['package'][$purchase['rank_a']]['max_dlot'];
			$max_wlot = $vars['package'][$purchase['rank_a']]['max_wlot'];
			$maintenance_lot = $vars['package'][$purchase['rank_a']]['maintenance'];
			$incentive_balance = $vars['package'][$purchase['rank_a']]['incentive'];
			//if($share_price<=0)
			//	$swallet = 0;
			//else
			//	$swallet = (floor($incentive_balance/$share_price));
			
			$sql = "INSERT INTO gg_member_mwallet_record SET uid=".$new_uid.",type='credit',amount=".$incentive_balance.",bal=".$incentive_balance.",descr='Purchase new package',cdate='$datetime'";
			mysql_query($sql);
			
			//buy machine
			$match_qty=0;
			$target=mysql_fetch_assoc(mysql_query("select * from gg_share_trading where type='sell' and qty>match_qty order by price, cdate"));		
			$amount = $incentive_balance;	
			
			while($amount>0){
				$qty = floor($amount/$target['price']);
				if($qty<=0) break;
				
				if($qty>($target['qty']-$target['match_qty'])){
					$deduct_qty = $target['qty']-$target['match_qty'];
				}else{
					$deduct_qty = $qty;
				}
				$deduct_amount = $deduct_qty * $target['price'];
				$amount-=$deduct_amount;
				$match_qty+=$deduct_qty;
				
				mysql_query("UPDATE gg_share_target SET buy_balance=buy_balance+".$deduct_qty." WHERE share_price=".$target['price']);
				mysql_query("INSERT INTO gg_member_mwallet_record (uid,type,amount,bal,descr,cdate) VALUES (".$new_uid.",'debit',".$deduct_amount.",".$amount.",'Buy ".$deduct_qty." machine with price ".$target['price']."','".$datetime."')");
				mysql_query("INSERT INTO gg_share_trading (uid,price,qty,match_qty,type,cdate) VALUES (".$new_uid.",".$target['price'].",".$deduct_qty.",".$deduct_qty.",'buy'".",'".$datetime."')");
				mysql_query("UPDATE gg_share_trading SET match_qty=match_qty+".$deduct_qty." WHERE id=".$target['id']);
				mysql_query("INSERT INTO gg_share_trading_ledger (trading_id, uid, buy_uid, sell_uid, price, qty, type, cdate) VALUES ('".$target['id']."', '".$target['uid']."', '".$new_uid."', '".$target['uid']."', '".$target['price']."', '".$deduct_qty."', 'sell', '".$datetime."')");
				mysql_query("INSERT INTO gg_share_trading_ledger (trading_id, uid, buy_uid, sell_uid, price, qty, type, cdate) VALUES ('".$target['id']."', '".$new_uid."', '".$new_uid."', '".$target['uid']."', '".$target['price']."', '".$deduct_qty."', 'buy', '".$datetime."')");
				
				$swallet_bal = @mysql_result(mysql_query("select swallet from $db->users where id='$new_uid'"), 0) or 0;
				$swallet_bal += $deduct_qty;
				mysql_query("INSERT INTO gg_member_swallet_record (uid, type, amount, bal, descr, cdate) values ('".$new_uid."','credit',".$deduct_qty.",".$swallet_bal.",'Buy machine. ".$deduct_qty." with price ".$target['price']."','".$datetime."')");
									
				$sell_ewallet_balance = mysql_result(mysql_query("select ewallet from gg_users where id=".$target['uid']), 0) or 0;
				$sell_mwallet_balance = mysql_result(mysql_query("select mwallet from gg_users where id=".$target['uid']), 0) or 0;
				$sell_ewallet_balance += $deduct_amount;
				mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$target['uid'].",'credit',".$deduct_amount.",".$sell_ewallet_balance.",'Sell machinese. ".$deduct_qty." X ".$target['price']." = ".$deduct_amount."','".$datetime."')");
				//only php 5.3 above can use PHP_ROUND_HALF_UP
				//$sell_fee = round($sell_amount*0.1, 2, PHP_ROUND_HALF_UP);
				$sell_fee = $deduct_amount*0.1;
				$sell_ewallet_balance -= $sell_fee;
				mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$target['uid'].",'debit',".$sell_fee.",".$sell_ewallet_balance.",'Sell machinese. ".$deduct_amount." X 10% = ".$sell_fee."','".$datetime."')");
				//all fees go to company
				$com_ewallet_balance = mysql_result(mysql_query("select ewallet from gg_users where id=9998"), 0) or 0;
				$com_ewallet_balance += $sell_fee;
				mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (9998,'credit',".$sell_fee.",".$com_ewallet_balance.",'".$target['uid']." sell machinese. ".$deduct_amount." X 10% = ".$sell_fee."','".$datetime."')");
				mysql_query("update gg_users set ewallet=".$com_ewallet_balance." where id=9998");
							
				if($target['uid']<>9999){					
					//30% repurchase share
					//$repurchase = (ceil((($sell_amount-$sell_fee)*0.3) * 100) / 100);
					$repurchase = ($deduct_amount-$sell_fee)*0.3;
					$sell_ewallet_balance -= $repurchase;
					$sell_mwallet_balance += $repurchase;
					mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$target['uid'].",'debit',".$repurchase.",".$sell_ewallet_balance.",'30% convert to MP account.','".$datetime."')");
					mysql_query("insert into gg_member_mwallet_record (uid,type,amount,bal,descr,cdate) values (".$target['uid'].",'credit',".$repurchase.",".$sell_mwallet_balance.",'30% convert from e-wallet account.','".$datetime."')");
				}
				mysql_query("update gg_users set ewallet=".$sell_ewallet_balance.",mwallet=".$sell_mwallet_balance." where id=".$target['uid']);
				
				if($amount>0){
					$target=mysql_fetch_assoc(mysql_query("select * from gg_share_trading where type='sell' and qty>match_qty order by price, cdate"));
					if($target['price']<=0) break;
				}
			}			
						
			mysql_query("update $db->users set swallet=".$match_qty.",mwallet=".$amount.",pool_share=".$total_cp.",max_dlot=".$max_dlot.",max_wlot=".$max_wlot.",maintenance_lot=".$maintenance_lot." where id=".$new_uid);

			//for those special case, get register point but no bonus payout
			$refund_bv = @mysql_result(mysql_query("select refund_bv from $db->users where id='$uid'"), 0) or 0;
			if($refund_bv>0){
				mysql_query("update $db->users set swallet=0, owallet='$price' where id='$new_uid'");
				
				mysql_query("update $db->users set refund_bv=refund_bv-".$price." where id='$uid'");
				
				mysql_query("update $db->purchase set total_bv=0, share_price=0 where id=".$purchase['id']);		
			}

			$activation_link="<a href='".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]'>".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]</a>";


			//email user


			$msg_style=$vars["css"]["msg_style"];


			$td_style=$vars["css"]["td_style"];


			$td_title_style=$vars["css"]["td_title_style"];


			$u_sub="$vars[title] - Thank You for Your Registration";

			$user_info=get_user_detail_by_id($new_uid);
			
			$user_table="


			<table align='center' ".$vars["css"]["table_style"]." width='100%'>


				<tr>


					<td $td_title_style colspan='2'>".__("Account Information")."</td>


				</tr>


				<tr>


					<td $td_style width='120'>".__("User ID")."</td>


					<td $td_style>$user_info[code]</td>


				</tr>


				<tr>


					<td $td_style>".__("Registered Screen Name")."</td>


					<td $td_style>$post_s[_username]</td>


				</tr>


				<tr>


					<td $td_style>".__("Level 1 Password")."</td>


					<td $td_style>$post_s[_password]</td>


				</tr>


				<tr>


					<td $td_style>".__("Level 2 Password")."</td>


					<td $td_style>$password2</td>


				</tr>


				<tr>


					<td $td_style>".__("Level 3 Password")."</td>


					<td $td_style>$password3</td>


				</tr>


				<tr>


					<td $td_style colspan=2>".__("From RMC Administration Robot")."</td>


				</tr>


				<tr>


					<td $td_style colspan=2>".__("Note: Please do not reply to this message as it will be automatically discarded.")."</td>


				</tr>


			</table>";
			
			$user_table2="


			<table align='center' ".$vars["css"]["table_style"]." width='100%'>


				<tr>


					<td $td_title_style colspan='2'>".__("Account Information")."</td>


				</tr>


				<tr>


					<td $td_style width='120'>".__("User ID")."</td>


					<td $td_style>$user_info[code]</td>


				</tr>


				<tr>


					<td $td_style>".__("Registered Screen Name")."</td>


					<td $td_style>$post_s[_username]</td>


				</tr>


				<tr>


					<td $td_style>".__("Level 1 Password")."</td>


					<td $td_style>$post_s[_password]</td>


				</tr>


			</table>";


			$u_msg=


			"<p $msg_style>Dear $post_s[_name], <br />\n<br />\nThank you for your registration. The user information for your new account is listed below:</p>


			$user_table";


			if(email_user($post_s["_email"], $u_sub, $u_msg)){


				$email_msg=replace_tag(__("A welcome email has been sent to '<%email%>'."), array("<%email%>"=>$post_h['_email']));


			}else{


				$email_errmsg=replace_tag(__("The Welcome email could not be sent to '<%email%>', please contact us for more information."), array("<%email%>"=>$post_h['_email']));


			}





			//email referrer


			if($post_s["ref"]){


				$r_sub=$vars["title"]." - You have just sponsored a new member in your downline group!";


				$r_msg=


				"<p>Dear $r_ref[name],</p>


				<p>Congratulations! You have just sponsored a new member in your downline group. The member details of your new downline are as below:</p>


				<p>Downline ID: $user_info[code]<br />\nName: $user_info[name]</p>


				<p>You can check your network <a href='".M_URL."/members/".$vars["file"]["member"]["genealogy"]."'>here</a>. Keep up the good work!</p>";


				email_user($r_ref["email"], $r_sub, $r_msg);


			}


		}


		if(!$errmsg){


			$_SESSION["user_register"]=false;


			$msg=__("Thank you for your registration.")." ".($email_msg? $email_msg : "<span class='red'>$email_errmsg</span>")."<br />\n";


			print format_member_page(str_replace("<%tab_content%>", "<h2>$page_title</h2>".format_msg($msg)."<p>".__("The user information of your account is listed below:")."</p>$user_table2", $tab), $this_title, $content_title, $css);


			exit();


		}


	}





	$errmsg=$errmsg? format_err($errmsg) : "";


	


	if($critical_error){echo $critical_error;


		$a_sub = "$vars[title] - User Registration Error";


		$a_msg = 


		"<p>Dear admin,</p>


		<p>Error occur while member id#$uid register a new member, error below:</p>


		$critical_error";


		email_admin($a_sub, $a_msg, 'e');


	}


}


$_SESSION["user_register"]=true;

$link_select=build_select($r_link, $r_link_d, $uid, 'main_link', $inputbox_style);

if($post_s["reentry"]=='1' || $get_s["reentry"]=='1'){
	$r_user=get_user_detail_by_id($uid);
	$dob = split('-',$r_user["dob"]);
	$form_fields=array("acc_type"=>"p","ref"=>$r_user['code'],"matrix_upline"=>$r_user['code'],"matrix_position"=>"","payment_channel"=>"ewallet","package"=>"","_person_in_charge"=>"","_bis_reg"=>"","_signup_code"=>"","_username"=>"","_name"=>$r_user['name'],"_password"=>"","password2"=>"","_email"=>$r_user['email'],"_ic"=>$r_user['ic'],"_address"=>$r_user['address'],"_address2"=>$r_user['address2'],"_city"=>$r_user['city'],"_zip"=>$r_user['zip'],"_state"=>$r_user['state'],"country"=>$r_user['country'],"_homeno"=>$r_user['homeno'],"_mobileno"=>$r_user['mobileno'],"_officeno"=>$r_user['officeno'],"_faxno"=>$r_user['faxno'],"dob_day"=>$dob[2],"dob_month"=>$dob[1],"dob_year"=>$dob[0],"gender"=>$r_user['gender'],"_bank_name"=>$r_user['bank_name'],"_bank_acc_no"=>$r_user['bank_acc_no'],"_bank_swiftcode"=>$r_user['bank_swiftcode'],"_bank_branch"=>$r_user['bank_branch'],"terms"=>"");
	
	$link_content="<tr>


			<td>".__("Link with main account").__(":")." ".__("*")."</td>


			<td>$link_select</td>


		</tr>";
}else{
	$form_fields=array("acc_type"=>"p","ref"=>$r_user['code'],"matrix_upline"=>$r_user['code'],"matrix_position"=>"","payment_channel"=>"ewallet","package"=>"","_person_in_charge"=>"","_bis_reg"=>"","_signup_code"=>"","_username"=>"","_name"=>"","_password"=>"","password2"=>"","_email"=>"","_ic"=>"","_address"=>"","_address2"=>"","_city"=>"","_zip"=>"","_state"=>"","country"=>"HK","_homeno"=>"","_mobileno"=>"","_officeno"=>"","_faxno"=>"","dob_day"=>"","dob_month"=>"","dob_year"=>"","gender"=>"m","_bank_name"=>"","_bank_acc_no"=>"","_bank_swiftcode"=>"","_bank_branch"=>"","terms"=>"");
	$link_content="";	
}




foreach($form_fields as $field => $default){


	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;


	$dis[$field]=!$posting? $default : $post_h[$field];


}


if($get_s["pos"]){
	$dis['matrix_position'] = $get_s["pos"];
}

if($get_s["upline"]){
	$dis['matrix_upline'] = $get_s["upline"];
}


$position_select=build_select($r_position, $r_position_d, $dis['matrix_position'], 'matrix_position', $inputbox_style);


$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", $inputbox_style);


$gender_select=build_select($r_gender, $r_gender_d, $dis["gender"], "gender", $inputbox_style);


$dob_input=generate_dmy_input("dob", $dis["dob_day"], $dis["dob_month"], $dis["dob_year"], "class='inputbox' width='100' style='width: 100px'");


//$payment_channel_select=build_select($r_payment_channel, $r_payment_channel_d, $dis['payment_channel'], 'payment_channel', $inputbox_style);


//$package_select=build_select($r_package, $r_package_d, $dis['package'], 'package', "style='width:100%;'");





//referrer


if($dis["ref"]){


	if($r=get_user_detail_by_code($dis["ref"])){


		$ref_text="<span class='bold'>".replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$r["code"], "<%name%>"=>$r["name"]))."</span>";


	}else{


		$ref_text="<span class='red'>".__("Invalid Sponsor")."</span>";


	}


}


if($dis["matrix_upline"]){


	if($r=get_user_detail_by_code($dis["matrix_upline"])){


		$up_text="<span class='bold'>".replace_tag(__("Upline ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$r["code"], "<%name%>"=>$r["username"]))."</span>";


	}else{


		$up_text="<span class='red'>".__("Invalid Upline")."</span>";


	}


}





//javascript


$jvscript=


"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>


<script type='text/javascript'>


jQuery(document).ready(function(j){


 j('form[@name=member_form],form[@name=member_form2]').submit(function(){


  j('input[@name=submit_btn]').attr('disabled','disabled');


 });





 j('input#check_ref_btn').click(function(){


  j('span#ref_text').html('').removeClass('red');


  if(j('input[@name=ref]').val()==''){


   j('span#ref_text').html('".AddSlashes(__("Please provide a Sponsor ID!"))."').addClass('red');


  }else{


   j('span#ref_text').html('Checking...');


   j(this).attr('disabled','disabled');


   j.ajax({


    url: '$this_file?aj=1&check_ref=1',


    data: {'ref': j('input[@name=ref]').val()},


    type: 'post',


    dataType: 'xml',


    error: function(){


     j('span#ref_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');


    },


    success: function(data){


     var mesg='';


     if(j('loggedout', data).text()=='loggedout'){


      mesg='".AddSlashes(__("You have been logged out."))."';


     }else{


      j(data).find('msg').each(function(){


       mesg+=j(this).text()+' ';


      });


     }


     var status=j(data).find('status').text();


     j('span#ref_text').html(mesg).addClass(status==1? 'bold' : 'red');


    },


    complete: function(){


     j('input#check_ref_btn').attr('disabled','');


    }


   });


  }


 });


 


 j('input#check_up_btn').click(function(){


  j('span#up_text').html('').removeClass('red');


  if(j('input[@name=matrix_upline]').val()==''){


   j('span#up_text').html('".AddSlashes(__("Please provide a Upline ID!"))."').addClass('red');


  }else{


   j('span#up_text').html('Checking...');


   j(this).attr('disabled','disabled');


   j.ajax({


    url: '$this_file?aj=1&check_upline=1',


    data: {'ref': j('input[@name=matrix_upline]').val()},


    type: 'post',


    dataType: 'xml',


    error: function(){


     j('span#up_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');


    },


    success: function(data){


     var mesg='';


     if(j('loggedout', data).text()=='loggedout'){


      mesg='".AddSlashes(__("You have been logged out."))."';


     }else{


      j(data).find('msg').each(function(){


       mesg+=j(this).text()+' ';


      });


     }


     var status=j(data).find('status').text();


     j('span#up_text').html(mesg).addClass(status==1? 'bold' : 'red');


    },


    complete: function(){


     j('input#check_up_btn').attr('disabled','');


    }


   });


  }


 });


});





function update_acc_type(type){


 if(type=='p'){


  personal_d='block';


  company_d='none';


 }else{


  personal_d='none';


  company_d='block';


 }


 q('acctype_personal').style.display=personal_d;


 q('acctype_personal_home').style.display=personal_d;


 q('acctype_company').style.display=company_d;


}





function goback(){


	q('__edit').value = 1;


	q('__confirm').value = '';


	document.member_form2.submit();


}

function MM_openBrWindow(theURL,features) {
	//var width_height = features.split(',');	
  	//var lf = (screen.width - 480)/2;
	//var tf = (screen.height - 350)/2;
	//var sizeIt = 'width=400,height=250,scrollbars=yes,resizable=no,top='+tf+',left='+lf;
	//win = window.open(theURL,'mywindow',sizeIt);
	//if (window.focus) 
	//{
	//	win.focus();
	//}
}



</script>";





//content jvscript


$c_jvscript=


"<script type='text/javascript'>


update_acc_type('$dis[acc_type]');


</script>";





$display_fields=array("_signup_code","ref","matrix_upline","_person_in_charge","_bis_reg","_username","_name","_password","_email","_ic","_address","_address2","_city","_zip","_state","_homeno","_mobileno","_officeno","_faxno","_bank_name","_bank_acc_no","_bank_swiftcode","_bank_branch");


foreach($form_fields as $field => $default){


	if(in_array($field, $display_fields)){


		$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;


		$dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);


		$readonly=$textarea=$password=false;


		if(!$preview){


			if($field=='matrix_upline'){


				$readonly=true;


			}elseif($field=='_bank_branch'){


				$extra_display="<tr><td></td><td><table><tr><td><input type='checkbox' name='terms' ".($dis["terms"]? "checked='checked'" : "")." id='chk_terms' onchange='MM_openBrWindow(\"http://RMC.co/tnc.html\",\"width=480,height=600\")'/></td><td><label for='chk_terms'>".replace_tag(__("I have read and agreed to the <%link%>Terms of Service<%/link%> of <%title%>."), array("<%link%>"=>"<a href='".$vars["file"]["public"]["terms"]."' target='_blank'>", "<%/link%>"=>"</a>", "<%title%>"=>__($vars["title"])))."</label></td></tr></table></td></tr>";


			}else{


				$extra_display='';


			}


		}else{


			$extra_display='';


		}


		if(in_array($field, array("_password","_sec_password"))){


			$password=true;


		}


		$readonly_str=$readonly? "readonly='readonly'" : "";


		$form_inputfield[$db_fieldname]="


		<tr id='input_$db_fieldname'>


			<td width='$td_width'><div style='width:".$td_width."px;'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</div></td>


			<td>".($preview? ($dis[$field]? $dis[$field] : '&nbsp;') : ($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "


			<input type='".($password? "password" : "text")."' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />"))."$extra_display</td>


		</tr>";


	}


}





//##### PREVIEW #####


if($preview){


	foreach($post_h as $f=>$v){


		$hidden_fields.="<input type='hidden' name=\"$f\" value=\"$v\" />\n";


	}


	$register="


	<form name='member_form2' method='post' action='$this_file'>


	<input type='hidden' name='__req' value='1' />


	<input type='hidden' name='__edit' />


	<input type='hidden' name='__confirm' value='1' />


	$hidden_fields


	<p>".__('Please review your particulars and when you are confirm please click the Register button.')."</p>


	<table class='pbt_table rev'>


		<tr class='pbt_header'>


			<td colspan='2'>".__("Account Information")."</td>


		</tr>  


		$form_inputfield[signup_code]


		<tr>


			<td>".__("Package").__(":")." ".__("*")."</td>


			<td>".$vars['rank_index_a_d'][$purchase["rank_a"]]."</td>


		</tr>


		<tr style='display:none'>


			<td>".__("Account Type").__(":")." ".__("*")."</td>


			<td>".($dis['acc_type']=="p"? __("Personal") : __("Company"))."</td>


		</tr>


		$form_inputfield[ref]


		$form_inputfield[matrix_upline]


		<tr>


			<td>".__("Placement Position").__(":")." ".__("*")."</td>


			<td>$dis[matrix_position]</td>


		</tr>


		$form_inputfield[username]


		<tr>


			<td>".__("Password").__(":")." ".__("*")."</td>


			<td><span class='italic'>".__("Not Displayed")."</td>


		</tr>


		$form_inputfield[name]


		$form_inputfield[email]".($dis['acc_type']=='p'? "


		$form_inputfield[ic]


		<tr>


			<td>".__("Gender").__(":")." ".__("*")."</td>


			<td>{$r_gender_d[$dis['gender']]}</td>


		</tr>


		<tr>


			<td>".__("Date of Birth").__(":")." ".__("*")."</td>


			<td>$dis[dob_day]-$dis[dob_month]-$dis[dob_year]</td>


		</tr>" : "


		$form_inputfield[bis_reg]


		$form_inputfield[person_in_charge]")."


		$form_inputfield[address]


		$form_inputfield[address2]


		$form_inputfield[city]


		$form_inputfield[zip]


		$form_inputfield[state]


		<tr>


			<td>".__("Country").__(":")." ".__("*")."</td>


			<td>{$country_code_d[$dis['country']]}</td>


		</tr>".($dis['acc_type'] == 'p'? "


		$form_inputfield[homeno]" : "")."


		$form_inputfield[mobileno]


		$form_inputfield[officeno]


		$form_inputfield[faxno]


		<tr class='pbt_header'>


			<td colspan='2'>".__("Payment Information").__(":")." ".__("*")."</td>


		</tr>


		$form_inputfield[bank_name]


		$form_inputfield[bank_acc_no]


		$form_inputfield[bank_swiftcode]


		$form_inputfield[bank_branch]


	</table>


	<table class='pbt_table'>


		<tr>


			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>


			<input type='button' name='back_btn' value=\"".__("Back")."\" onclick=\"goback();\" />


			<input type='submit' name='submit_btn' value=\"".__("Register")."\" />


			</td>


		</tr>


	</table>";


	//##### FIRST TIME #####


}else{


	$register=($errmsg?


	"$errmsg" : "")."


	<form name='aj_form' method='post' action='$this_file'></form>


	<form name='member_form' method='post' action='$this_file'>


	<input type='hidden' name='__req' value='1' />


	<table class='pbt_table'>


		<tr class='pbt_header'>


			<td colspan='2'>".__("Account Information")."</td>


		</tr>   


		<tr style='display:none'>


			<td>".__("Account Type").__(":")." ".__("*")."</td>


			<td><table><tr><td><input type='radio' name='acc_type' value=\"p\" id='accp' class='no_bg' ".($dis['acc_type']=="p"? "checked='checked'" : "")." onclick='update_acc_type(this.value);' onkeydown='update_acc_type(this.value);' /><label for='accp'>".__("Personal")."</label></td><td>&nbsp;</td>


			<td><input type='radio' name='acc_type' value=\"c\" id='accc' class='no_bg' ".($dis['acc_type']=="c"? "checked='checked'" : "")." onclick='update_acc_type(this.value);' onkeydown='update_acc_type(this.value);' /><label for='accc'>".__("Company")."</label></td></tr></table>


			</td>


		</tr>


		$form_inputfield[signup_code]


		$form_inputfield[ref]


		$form_inputfield[matrix_upline]


		<tr>


			<td>".__("Placement Position").__(":")." ".__("*")."</td>


			<td>$position_select</td>


		</tr>


		$link_content


		$form_inputfield[username]


		$form_inputfield[password]


		<tr>


			<td>".__("Confirm Password").__(":")." ".__("*")."</td>


			<td><input type='password' name='password2' $inputbox_style value=\"$dis[password2]\"></td>


		</tr>


		$form_inputfield[name]


		$form_inputfield[email]


	</table>


	<div id='acctype_personal'>


	<table class='pbt_table'>


		$form_inputfield[ic]


		<tr>


			<td>".__("Gender").__(":")." ".__("*")."</td>


			<td>$gender_select</td>


		</tr>


		<tr>


			<td>".__("Date of Birth").__(":")." ".__("*")."</td>


			<td>$dob_input</td>


		</tr>


	</table>


	</div>


	<div id='acctype_company'>


	<table class='pbt_table'>


		$form_inputfield[bis_reg]


		$form_inputfield[person_in_charge]


	</table>


	</div>


	<table class='pbt_table'>


		$form_inputfield[address]


		$form_inputfield[address2]


		$form_inputfield[city]


		$form_inputfield[zip]


		$form_inputfield[state]


		<tr>


			<td>".__("Country").__(":")." ".__("*")."</td>


			<td>$country_select</td>


		</tr>


	</table>


	<div id='acctype_personal_home'>


	<table class='pbt_table'>


		$form_inputfield[homeno]


	</table>


	</div>


	<table class='pbt_table'>


		$form_inputfield[mobileno]


		$form_inputfield[officeno]


		$form_inputfield[faxno]


		<tr class='pbt_header'>


			<td colspan='2'>".__("Payment Information").__(":")." ".__("*")."</td>


		</tr>


		$form_inputfield[bank_name]


		$form_inputfield[bank_acc_no]


		$form_inputfield[bank_swiftcode]


		$form_inputfield[bank_branch]


		<tr>


			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>


			<input type='submit' name='submit_btn' value=\"".__("Register")."\" />


			</td>


		</tr>


	</table>


	$c_jvscript";


}





$css.="


<style type='text/css'>


td{


	font-size:12px;


}





table.rev td{


	border:1px solid #000;


}


</style>";





$content="<h2>$page_title</h2>$register";


$content=str_replace("<%tab_content%>", $content, $tab);



print format_member_page($content, $this_title, $content_title, $css.$jvscript);

?>